import { loadScript, loadStyle } from '@/utils/handlePlatform/loadSource';
import setAttributes from '@/utils/handlePlatform/setAttributes';
import configJson from '../pluginTemp/config.json';

const isEnvProduction = import.meta.env.PROD;
const onlineDevelopmentMode = import.meta.env.VITE_APP_ONLINE_DEVELOPMENT_MODE === 'true';

if (isEnvProduction || (onlineDevelopmentMode && !window.online_development_islocal)) {
  if (!window.CUSTOM_PLUGIN) {
    window.CUSTOM_PLUGIN = new Map();
  }
  window.CUSTOM_PLUGIN.set(configJson.id, (dom, props, context, eventBus) => {
    loadSource(async () => {
      const App = await import('./App.vue');
      if (dom.childNodes.length > 0) {
        dom.removeChild(dom.childNodes[0]);
      }
      props = setAttributes(dom, props);
      props.eventBus = eventBus;
      Vue3.createApp(Vue3.h(App.default, props)).use(ElementPlus).mount(dom);
    });
  });
} else if (onlineDevelopmentMode && window.online_development_islocal) {
  loadSource(async () => {
    const { OnlineDevelopmentModeDetails } = await import('@/components');
    Vue3.createApp(OnlineDevelopmentModeDetails).use(ElementPlus).mount('#app');
  });
} else {
  loadSource(async () => {
    const { Development } = await import('@/components');
    Vue3.createApp(Development).use(ElementPlus).mount('#app');
  });
}

function loadSource(callback) {
  /* 因性能需要，所有二开使用的vue实例为同一个实例，使用的vue版本为3.4.5，element-plus版本为2.4.3，如果需要使用其他版本，请自行下载并替换掉pluginTemp/source/vue/vue.prod.js */
  loadScript(`vue/vue.prod.js`, 'Vue3Ref', 'Vue3').then(() => {
    Promise.all([loadScript(`element-plus/index.min.js`, 'ElementPlusRef', 'ELEMENTPLUS')]).then(
      () => callback(),
    );
  });
  loadStyle(`element-plus/index.css`, 'ElementPlusStyleRef');
}
